package com.os.lambda.chapter9;

import com.sun.xml.internal.ws.resources.HandlerMessages;
import lombok.Data;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.net.NetSocket;
import org.vertx.java.platform.Verticle;

import java.nio.Buffer;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;

@Data
public class User implements Handler<Buffer> {

    private static final Pattern newLine = Pattern.compile("\\n");
    private final NetSocket socket;
    private final Set<String> names;
    private final EventBus eventBus;

    private Optional<String> name;


    public User(NetSocket socket, Verticle verticle) {
        Vertx vertx = verticle.getVertx();
        this.socket = socket;
        names = vertx.sharedData().getSet("names");
        eventBus = vertx.eventBus();
        name = Optional.empty();
    }


    @Override
    public void handle(Buffer buffer) {
        newLine.splitAsStream(buffer.toString())
                .forEach(line->{
                    if(!name.isPresent())
                        setName(Optional.ofNullable(line));
                    //else
                        //new HandlerMessages(line);
                });
    }
}
